package com.gljx.web.controller;

import com.gljx.constant.ActivitiKey;
import com.gljx.util.*;
import com.gljx.web.Entity.*;
import com.gljx.web.service.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/")
public class TrainChargeEntryController {


	//自动注入
	@Autowired
	private TrainChargeEntryService trainChargeEntryService;

	//自动注入
	@Autowired
	private DepartmentService departmentService;

	//自动注入
	@Autowired
	private CustomLogService customLogService;

	//自动注入
	@Autowired
	private StudentController studentController;

	//自动注入
	@Autowired
	private TrainChargeService trainChargeService;

	@Autowired
	StudentService studentService;
    @Autowired
	PersonService personService;
	//自定义流程工具
	private Axamine axamine = new Axamine();
	/**
	 * 查询培训收费
	 * @param request
	 * @return
	 */
	@RequestMapping("/queryTrainCharge/look.action")
	public String queryTrainCharge(HttpServletRequest request,String type){
		PageBean<TrainCharge> pb = new PageBean<>();
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//时间格式化
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		//获取当前时间
		String endTime = sdf.format(new Date());
		//获取前三天
		String beginTime = TimeFormat.getThreeDay();
		try {
			//获取分页
			pb = getPageBean(request,user.getFcompanyid(),beginTime,endTime);
			//获取当前分页的值
			List<TrainCharge> trainCharges = pb.getBeanList();
			//新建一个List<TrainChargeEntry>
//			List<TrainChargeEntry> trainChargeEntries=new ArrayList<>();
			for (TrainCharge trainCharge : trainCharges) {
				//获取子类信息
				List<TrainChargeEntry> trainChargeEntrys = trainChargeEntryService.queryTrainChargeEntry(trainCharge.getFid(), "", "", "");

				//直接用for循环
				for(int i=0;i<trainChargeEntrys.size();i++){
					//如果实收培训不为null
					if(trainChargeEntrys.get(i).getSspxf()==null){
				        //如果子表集合的里面优惠费用不为null
						   if(trainChargeEntrys.get(i).getCfyhje()!=null){
							   trainChargeEntrys.get(i).setSspxf((trainChargeEntrys.get(i).getCfpxf().subtract(trainChargeEntrys.get(i).getCfyhje())));
						   }else{
							   trainChargeEntrys.get(i).setSspxf(trainChargeEntrys.get(i).getCfpxf());
						   }

					}
				}

//				  for(TrainChargeEntry trainChargeEntry: trainChargeEntrys){
//                    //BigDecimal类的减法处理
//				  	if(trainChargeEntry.getCfyhje()!=null){
//					  trainChargeEntry.setSspxf((trainChargeEntry.getCfpxf().subtract(trainChargeEntry.getCfyhje())));
//				  	}else{
//				  		trainChargeEntry.setSspxf(trainChargeEntry.getCfpxf());
//					}
//					trainChargeEntries.add(trainChargeEntry);
//				 }这个方法有问题，没有都会重复输入

				//放入集合
				trainCharge.setTrainChargeEntrys(trainChargeEntrys);
			}
			//合计信息总数
			String messageAmount="共有"+pb.getTr()+"条消息";
			//把获取到的数据传回页面
			request.setAttribute("messageAmount",messageAmount);
			request.setAttribute("trainCharges", trainCharges);
			request.setAttribute("pb", pb);
			request.setAttribute("beginTime", beginTime);
			request.setAttribute("endTime", endTime);
			request.setAttribute("flag", type);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "/backHome/financialManagement/trainCharge/trainChargeList";
	}

	/**
	 * 根据条件查询
	 * @param request
	 * @param studentName 学生名
	 * @param cfidcardno 身份证号
	 * @param cftjr 推荐人
	 * @param beginTime 开始时间
	 * @param endTime 结束时间
	 * @return
	 */
	@RequestMapping("/queryTrainChargeByinfo")
	public String queryTrainChargeByinfo(HttpServletRequest request,
			String studentName,String cfidcardno,String cftjr,String beginTime,String endTime){
		PageBean<TrainCharge> pb = new PageBean<>();
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		try {
			//去除空格
			studentName = studentName.trim();
			cfidcardno = cfidcardno.trim();
			cftjr = cftjr.trim();
			//查询分页数据
			pb = getPageBean2(request,user.getFcompanyid(),studentName,cfidcardno,cftjr,beginTime,endTime);
			//获取数据
			List<TrainCharge> trainCharges = pb.getBeanList();
			//新建一个List<TrainChargeEntry>
//			List<TrainChargeEntry> trainChargeEntries=new ArrayList<>();
			for (TrainCharge trainCharge : trainCharges) {
				//获取子类信息
				List<TrainChargeEntry> trainChargeEntrys = trainChargeEntryService.queryTrainChargeEntry(trainCharge.getFid(), "", "", "");
				//直接用for循环
				for(int i=0;i<trainChargeEntrys.size();i++){
					//如果实收培训不为null
					if(trainChargeEntrys.get(i).getSspxf()==null){
						//如果子表集合的里面优惠费用不为null
						if(trainChargeEntrys.get(i).getCfyhje()!=null){
							trainChargeEntrys.get(i).setSspxf((trainChargeEntrys.get(i).getCfpxf().subtract(trainChargeEntrys.get(i).getCfyhje())));
						}else{
							trainChargeEntrys.get(i).setSspxf(trainChargeEntrys.get(i).getCfpxf());
						}

					}
				}
//
//				//为了改变实收培训费的值,新增一个新循环;
//				for(TrainChargeEntry trainChargeEntry: trainChargeEntrys){
//					//BigDecimal类的减法处理
//					//判断优惠金额是否为空
//					if(trainChargeEntry.getCfyhje()!=null){
//						trainChargeEntry.setSspxf((trainChargeEntry.getCfpxf().subtract(trainChargeEntry.getCfyhje())));
//					}else{
//						trainChargeEntry.setSspxf(trainChargeEntry.getCfpxf());
//					}
//					trainChargeEntries.add(trainChargeEntry);
//				}

				//放入集合
				trainCharge.setTrainChargeEntrys(trainChargeEntrys);
			}
			//合计信息总数
			String messageAmount="共有"+pb.getTr()+"条消息";
			//把获取到的数据传回页面
			request.setAttribute("messageAmount",messageAmount);
			request.setAttribute("trainCharges", trainCharges);
			request.setAttribute("studentName", studentName);
			request.setAttribute("cfidcardno", cfidcardno);
			request.setAttribute("cftjr", cftjr);
			request.setAttribute("beginTime", beginTime);
			request.setAttribute("endTime", endTime);
			request.setAttribute("pb", pb);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return "/backHome/financialManagement/trainCharge/trainChargeList";
	}


	/**
	 * 培训收费字段筛选
	 * @param p
	 * @param request
	 * @return
	 */
	@RequestMapping("/trainOutList")
	@ResponseBody
	public Object studentOutList(@RequestBody(required=true) Map<String,Object> p, HttpServletRequest request){
		ArrayList<String> arr= (ArrayList<String>) p.get("outList");
		request.getSession().setAttribute("trainOutList",arr);
		return arr;
	}






	/**
	 * 根据fid删除
	 * @param request
	 * @param deleteId 多个fid
	 * @param fid 单个fid
	 * @return
	 */
	@RequestMapping("/deleteTranChargeByFid")
	public String deleteTranChargeByFid(HttpServletRequest request, String deleteId[], String fid, String[] fnumber, String fnumber2) {
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//添加日志
		String time = TimeFormat.timeFormat(new Date());
		List<CustomLog> customLogs = new ArrayList<>();
		ActitiviUtil actitiviUtil = new ActitiviUtil();
		if (fid == null) {
			for (int i = 0; i < deleteId.length; i++) {
				List<TrainChargeEntry> trainChargeEntries = trainChargeEntryService.queryTrainChargeEntrysByFparentId(deleteId[i]);
				for (TrainChargeEntry trainChargeEntrie : trainChargeEntries) {
					CustomLog customLog2 = new CustomLog();
					customLog2.setFid(GetFid.UUIDIntoFid());
					customLog2.setFcreatetime(time);
					customLog2.setFcreatorid(user.getFid());
					customLog2.setCfstudentid(trainChargeEntrie.getCfstudentid());
                    customLog2.setFnameL2("培训收费");
                    customLog2.setFdescriptionL2("删除学员:" + trainChargeEntrie.getCfstudentno() + trainChargeEntrie.getStudentName());
                    //控制单元
					customLog2.setFcontrolunitid(user.getFcompanyid());
					customLogs.add(customLog2);
				}
				//删除流程
				actitiviUtil.deleteTask(ActivitiKey.PUBLIC_KEY, fnumber[i]);
			}
		} else {
			List<TrainChargeEntry> trainChargeEntries = trainChargeEntryService.queryTrainChargeEntrysByFparentId(fid);
			//删除流程
			actitiviUtil.deleteTask(ActivitiKey.PUBLIC_KEY, fnumber2);
			for (TrainChargeEntry trainChargeEntrie : trainChargeEntries) {
				CustomLog customLog = new CustomLog();
				customLog.setFid(GetFid.UUIDIntoFid());
				customLog.setFcreatetime(time);
				customLog.setFcreatorid(user.getFid());
				customLog.setCfstudentid(trainChargeEntrie.getCfstudentid());
                customLog.setFnameL2("培训收费".trim());
                customLog.setFdescriptionL2("删除学员:" + trainChargeEntrie.getCfstudentno() + trainChargeEntrie.getStudentName());
                //控制单元
				customLog.setFcontrolunitid(user.getFcompanyid());
				customLogs.add(customLog);
			}
		}
		//删除
		trainChargeEntryService.deleteTranChargeByFid(deleteId, fid);
		customLogService.insertCustomLog(customLogs);
		//customLogService.addLog("财务管理", TimeFormat.timeFormat(new Date())+"对培训收费进行删除操作", null, user.getFid());
		//重定向到查询方法
		return "redirect:/DrivingSys/queryTrainCharge/look.action";
	}

	@ResponseBody
	@RequestMapping(value = "/selTrainByFnumber")
	public TrainChargeEntry selTrainByFnumber(HttpServletRequest request,String fnumber){
			TrainChargeEntry trainChargeEntry = new TrainChargeEntry();
			List<TrainChargeEntry> list = trainChargeEntryService.selTrainByFnumber(fnumber,GetUserSession.getUserSession(request));
			if(!list.isEmpty())
							 trainChargeEntry = list.get(0);
			return trainChargeEntry;
	}



	/**
	 * 跳转到添加页面
	 * @param request
	 * @return
	 */
	@RequestMapping("/insertTrainCharge")
	public String insertTrainCharge(HttpServletRequest request,String type){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//获取部门
		Department department = departmentService.queryAdminByFid(user.getFcompanyid());
		//获取最大编码
        /*String fnumber = customLogService.selectFunmber("ct_ds_traincharge",user.getFcompanyid());*/
		//获取下一个编码
        String number = GetFnumber.fnumbers("YW");
		//获取当前时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String endTime = sdf.format(new Date());
		String beginTime = TimeFormat.getMonth();
		try {
            Map map = studentController.getPageAsTrainCharge(request, "", "", "0","","","", beginTime, endTime);//调用学员方法
			request.setAttribute("flag", 1);				//是否为新增记录
			request.setAttribute("beginTime", beginTime);
			request.setAttribute("endTime", endTime);
			request.setAttribute("pb", map.get("pb"));
			request.setAttribute("students", map.get("sList"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//把数据传到页面
		request.setAttribute("name", user.getName());
		request.setAttribute("date", endTime);
		request.setAttribute("fnumber", number);
		request.setAttribute("department", department);
		request.setAttribute("type", type);
		return "/backHome/financialManagement/trainCharge/editTrainCharge";
	}

	/**
	 * 添加培训收费
	 * @param request
	 * @param trainCharge 属性自动封装
	 * @return
	 */
	@RequestMapping("/addTrainCharge")
	public String addTrainCharge(HttpServletRequest request,TrainCharge trainCharge){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//利用UUID生成fid
		trainCharge.setFid(GetFid.UUIDIntoFid());
		//控制单元id
		trainCharge.setFcontrolunitid(user.getFcompanyid());
		//创建人id
		trainCharge.setFcreatorid(user.getFid());
		//公司id
		trainCharge.setCfficompanyid(user.getFcompanyid());
		//获取当前时间
		String createTime = TimeFormat.timeFormat(new Date());
		//当前时间
		trainCharge.setFcreatetime(createTime);
		//操作人id
		trainCharge.setFhandlerid(user.getFid());
		//状态
        trainCharge.setCfbillstate(5L);
		//审核人id
		trainCharge.setFauditorid(user.getFid());
        //获取子类信息
		//序列
		String[] fseq = request.getParameterValues("fseq");
		//学员编码
		String[] cfstudentno = request.getParameterValues("cfstudentno");
		//学员id
		String[] cfstudentid = request.getParameterValues("cfstudentid");
		//学员姓名
		String[] studentName = request.getParameterValues("studentName");
		//学员性别
		String[] cfsex = request.getParameterValues("cfsex");
		//学员身份证号
		String[] cfidcardno = request.getParameterValues("cfidcardno");
		//学员身份证地址
		String[] cfidcardaddress = request.getParameterValues("cfidcardaddress");
		//推荐人
		String[] cftjr = request.getParameterValues("cftjr");
		//班级
		String[] cfclazz = request.getParameterValues("cfclazz");
		//班级金额
		String[] cfclazzamount = request.getParameterValues("cfclazzamount");
		//已收
		String[] cfyishou = request.getParameterValues("cfyishou");
		//应收
		String[] cfysje = request.getParameterValues("cfysje");
		//规费
		String[] cfguifei = request.getParameterValues("cfguifei");
		//培训费
		String[] cfpxf = request.getParameterValues("cfpxf");
		//现金
		String[] cfcash = request.getParameterValues("cfcash");
		//刷卡
		String[] cfcard = request.getParameterValues("cfcard");
		//挂账
		String[] cfguazhang = request.getParameterValues("cfguazhang");
		//银行转账
		String[] cfyhzz = request.getParameterValues("cfyhzz");
		//实收金额
		String[] cfshje = request.getParameterValues("cfshje");
		//优惠金额
		String[] cfyhje = request.getParameterValues("cfyhje");
		//优惠劵
		String[] cfyhj = request.getParameterValues("cfyhj");
		//欠费金额
		String[] cfqfje = request.getParameterValues("cfqfje");
		//备注
		String[] cfremark = request.getParameterValues("cfremark");
		//添加
		trainChargeService.addTrainCharge(trainCharge, fseq, cfstudentno, cfstudentid, cfsex, cfidcardno,cfidcardaddress, cftjr, cfclazz, cfclazzamount,
				cfyishou, cfysje, cfguifei, cfpxf, cfcash, cfcard, cfguazhang, cfyhzz, cfshje, cfyhje, cfyhj, cfqfje, cfremark);

		//添加日志
		List<CustomLog> customLogs = new ArrayList<>();
		for (int i = 0; i < cfstudentid.length; i++) {
			CustomLog customLog = new CustomLog();
			customLog.setFid(GetFid.UUIDIntoFid());
			customLog.setFcreatetime(createTime);
			customLog.setFcreatorid(user.getFid());
			customLog.setCfstudentid(cfstudentid[i]);
			customLog.setFnameL2("培训收费");
			customLog.setFdescriptionL2("新增学员:" + cfstudentno[i] + studentName[i] + "缴费金额：" + cfshje[i] + "单据编号:" + trainCharge.getFnumber());
			//控制单元
			customLog.setFcontrolunitid(user.getFcompanyid());
			customLogs.add(customLog);
		}
		customLogService.insertCustomLog(customLogs);
		//customLogService.addLog("财务管理", createTime+"对培训收费进行添加操作", null, user.getFid());
		//重定向到添加页面
		return "redirect:/DrivingSys/insertTrainCharge?type=3";
	}

	/**
	 * 根据fid查询
	 * @param request
	 * @param fid
	 * @return
	 */
	@RequestMapping("/selectTrainChargeByFid")
	public String selectTrainChargeByFid(HttpServletRequest request,String fid){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//获取部门
		Department department = departmentService.queryAdminByFid(user.getFcompanyid());
		//获取父类信息
		TrainCharge trainCharge = trainChargeService.queryByTrainChargeFid(fid);
		//查询子类信息
		List<TrainChargeEntry> trainChargeEntries = trainChargeEntryService.queryTrainChargeEntrysByFparentId(fid);
        if (trainCharge.getCfbillstate() == 5 || trainCharge.getCfbillstate() == 4) {
            request.setAttribute("sh", "5");
		}else{
			//获取当前时间
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String endTime = sdf.format(new Date());
			String beginTime = TimeFormat.getMonth();
			try {
                Map map = studentController.getPageAsTrainCharge(request, "", "", "0","","","", beginTime, endTime);//调用学员方法
				request.setAttribute("flag", 1);				//是否为新增记录
				request.setAttribute("beginTime", beginTime);
				request.setAttribute("endTime", endTime);
				request.setAttribute("pb", map.get("pb"));
				request.setAttribute("students", map.get("sList"));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
        //查询是否是经办人
        Axamine axamine = new Axamine();
        boolean state = axamine.selectAuditPerson(trainCharge.getFnumber());
        //把数据传到页面
        request.setAttribute("AuditState", state);
        request.setAttribute("trainChargeEntries", trainChargeEntries);
		request.setAttribute("department", department);
		request.setAttribute("trainCharge", trainCharge);
        request.setAttribute("key", ActivitiKey.PUBLIC_KEY);
        return "/backHome/financialManagement/trainCharge/editTrainCharge";
    }

	/**
	 * 修改培训收费
	 * @param request
	 * @param trainCharge
	 * @return
	 */
	@RequestMapping("/modifyTrainCharge")
	public String modifyTrainCharge(HttpServletRequest request,TrainCharge trainCharge){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//控制单元id
		trainCharge.setFcontrolunitid(user.getFcompanyid());
		//创建人id
		trainCharge.setFlastupdateuserid(user.getFid());
		//公司id
		trainCharge.setCfficompanyid(user.getFcompanyid());
		//获取当前时间
		String updateTime = TimeFormat.timeFormat(new Date());
		//当前时间
		trainCharge.setFlastupdatetime(updateTime);
		//操作人id
		trainCharge.setFhandlerid(user.getFid());

		trainCharge.setCfbillstate((long) 5);
		//审核人id
		trainCharge.setFauditorid(user.getFid());
		//获取子类信息
		//序列
		String[] fseq = request.getParameterValues("fseq");
		//学员编码
		String[] cfstudentno = request.getParameterValues("cfstudentno");
		//学员id
		String[] cfstudentid = request.getParameterValues("cfstudentid");
		//学员姓名
		String[] studentName = request.getParameterValues("studentName");
		//学员性别
		String[] cfsex = request.getParameterValues("cfsex");
		//学员身份证号
		String[] cfidcardno = request.getParameterValues("cfidcardno");
		//学员身份证地址
		String[] cfidcardaddress = request.getParameterValues("cfidcardaddress");
		//推荐人
		String[] cftjr = request.getParameterValues("cftjr");
		//班级
		String[] cfclazz = request.getParameterValues("cfclazz");
		//班级金额
		String[] cfclazzamount = request.getParameterValues("cfclazzamount");
		//已收
		String[] cfyishou = request.getParameterValues("cfyishou");
		//应收
		String[] cfysje = request.getParameterValues("cfysje");
		//规费
		String[] cfguifei = request.getParameterValues("cfguifei");
		//培训费
		String[] cfpxf = request.getParameterValues("cfpxf");
		//现金
		String[] cfcash = request.getParameterValues("cfcash");
		//刷卡
		String[] cfcard = request.getParameterValues("cfcard");
		//挂账
		String[] cfguazhang = request.getParameterValues("cfguazhang");
		//银行转账
		String[] cfyhzz = request.getParameterValues("cfyhzz");
		//实收金额
		String[] cfshje = request.getParameterValues("cfshje");
		//优惠金额
		String[] cfyhje = request.getParameterValues("cfyhje");
		//优惠劵
		String[] cfyhj = request.getParameterValues("cfyhj");
		//欠费金额
		String[] cfqfje = request.getParameterValues("cfqfje");
		//备注
		String[] cfremark = request.getParameterValues("cfremark");
		//添加
		trainChargeService.modifyTrainCharge(trainCharge, fseq, cfstudentno, cfstudentid, cfsex, cfidcardno,cfidcardaddress, cftjr, cfclazz, cfclazzamount,
				cfyishou, cfysje, cfguifei, cfpxf, cfcash, cfcard, cfguazhang, cfyhzz, cfshje, cfyhje, cfyhj, cfqfje, cfremark);
		//添加日志
		List<CustomLog> customLogs = new ArrayList<>();
		for (int i = 0; i < cfstudentid.length; i++) {
			CustomLog customLog = new CustomLog();
			customLog.setFid(GetFid.UUIDIntoFid());
			customLog.setFcreatetime(updateTime);
			customLog.setFcreatorid(user.getFid());
			customLog.setCfstudentid(cfstudentid[i]);
			customLog.setFnameL2("培训收费");
			customLog.setFdescriptionL2("修改学员:" + cfstudentno[i] + studentName[i] + "缴费金额：" + cfshje[i] + "单据编号:" + trainCharge.getFnumber());
			//控制单元
			customLog.setFcontrolunitid(user.getFcompanyid());
			customLogs.add(customLog);
		}
		customLogService.insertCustomLog(customLogs);
		//customLogService.addLog("财务管理", updateTime+"对培训收费修改添加操作", null, user.getFid());
		//重定向到查询方法
		return "redirect:/DrivingSys/queryTrainCharge/look.action?type=4";
	}

	/**
	 * 审核培训收费
	 * @param request
	 * @param fid
	 * @return
	 */
	@RequestMapping("/auditTrainCharge")
	@ResponseBody
    public int auditTrainCharge(HttpServletRequest request, String fid, String type, String message, String state, String fnumber,
								@RequestParam(value = "studentName[]", defaultValue = "") String[] studentName,
								@RequestParam(value = "studentId[]", defaultValue = "") String[] studentId,
								@RequestParam(value = "cfstudentno[]", defaultValue = "") String[] cfstudentno) {
		TrainCharge trainCharge = new TrainCharge();
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//修改人
		trainCharge.setFlastupdateuserid(user.getFid());
		if("1".equals(type)){
            ServerResponse serverResponse = axamine.auditProcess(fnumber, state, message);
            if (serverResponse.getStatus() == 1) {
                //审核人id
                trainCharge.setFauditorid(user.getFid());
                //状态
                trainCharge.setCfbillstate(5L);
                //fid
                trainCharge.setFid(fid);
                List<TrainChargeEntry> trainChargeEntries = trainChargeEntryService.queryTrainChargeEntrysByFparentId(fid);
                //添加日志
				customLogService.batchInsertState(studentName, studentId, "培训收费", cfstudentno, "单据编号:" + fnumber, "审核");
				//结束
				return trainChargeService.auditTrainCharge(trainChargeEntries, trainCharge);
			} else if (serverResponse.getStatus() == 2) {
				//推进
                if (!"1".equals(state)) {
                    //状态
                    trainCharge.setCfbillstate(3L);
                    //fid
                    trainCharge.setFid(fid);
					List<TrainChargeEntry> trainChargeEntries = trainChargeEntryService.queryTrainChargeEntrysByFparentId(fid);
					trainChargeService.updateTrainCharge(trainChargeEntries,trainCharge);
                }
                return 2;
			} else {
				//错误
				return 0;
			}
		}else{
			axamine.againstAuditProcess(fnumber, message);
			//审核人id
			trainCharge.setFauditorid(user.getFid());
			//状态
            trainCharge.setCfbillstate(3L);
            //fid
            trainCharge.setFid(fid);
            //添加日志
			customLogService.batchInsertState(studentName, studentId, "培训收费", cfstudentno, "单据编号:" + fnumber, "反审核");
			//修改
			List<TrainChargeEntry> trainChargeEntries = trainChargeEntryService.queryTrainChargeEntrysByFparentId(fid);
            return trainChargeService.updateTrainCharge(trainChargeEntries,trainCharge);
        }
    }

	/**
	 * 提交
	 * @param fnumber
	 * @param fid
	 * @param request
	 * @return
	 */
	@RequestMapping("/submitTrainCharge")
	@ResponseBody
    public int submitTrainCharge(String fid, HttpServletRequest request, String fnumber, String auditState,
								 @RequestParam(value = "studentName[]", defaultValue = "") String[] studentName,
								 @RequestParam(value = "studentId[]", defaultValue = "") String[] studentId,
								 @RequestParam(value = "cfstudentno[]", defaultValue = "") String[] cfstudentno) {
		TrainCharge trainCharge = new TrainCharge();
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		//状态
        trainCharge.setCfbillstate(4L);
		//修改人
		trainCharge.setFlastupdateuserid(user.getFid());
		//fid
        trainCharge.setFid(fid);
		//创建流程
        axamine.submissionProcess(fnumber, auditState);
		//添加日志
		customLogService.batchInsertState(studentName, studentId, "培训收费", cfstudentno, "单据编号:" + fnumber, "提交");
		//修改
		List<TrainChargeEntry> trainChargeEntries = trainChargeEntryService.queryTrainChargeEntrysByFparentId(fid);
		return trainChargeService.updateTrainCharge(trainChargeEntries,trainCharge);
    }

    @SuppressWarnings("unchecked")
	/**
	 * 返回PageBean实体类  包括记录总数，页码，每页记录集等  dmz 20160921
	 * @return 返回PageBean实体类
	 * @throws Exception
	 */
	public PageBean<TrainCharge> getPageBean2(HttpServletRequest request,String companyId,
			String studentName,String cfidcardno,String cftjr,String beginTime,String endTime) throws Exception
	{

		int offset;//从第几条数据开始加载
		if(request.getParameter("pager.offset")==null){
			offset=0;
		}else{
			offset=Integer.parseInt(request.getParameter("pager.offset"));
		}
		//拼接SQL语句
		StringBuffer psql = new  StringBuffer();
		psql.append("select distinct t.fid,t.fnumber,t.fdescription,to_char(t.fbizdate,'yyyy-MM-dd')fbizdate,u.name zdrName,us.name shName,t.cfbillstate,t.cfdycs,a.fname_l2 companyName ");
		psql.append(" from ct_ds_traincharge t left join t_e_user u  on t.fcreatorid=u.fid left join t_e_user us on t.fauditorid = us.fid  left join ct_ds_admin a on t.cfficompanyid =a.fid");
		psql.append(" left join ct_ds_trainchargeentry tr on t.fid = tr.fparentid left join ct_ds_student s on tr.cfstudentid = s.fid ");
		psql.append(" where t.FCONTROLUNITID= '"+companyId+"'");
		if("".equals(studentName)){

		}else{
			psql.append(" and s.fname_l2 like '%"+studentName+"%'");
		}
		if("".equals(cfidcardno)){

		}else{
            psql.append(" and tr.cfidcardno like '%" + cfidcardno + "%'");
        }
		if("".equals(cftjr)){

		}else{
			psql.append(" and tr.cftjr like '%"+cftjr+"%'");
		}
		if("".equals(beginTime) || "".equals(endTime)){

		}else{
			psql.append("  and t.fbizdate between to_date('"+beginTime+"','YYYY/MM/DD') and to_date('"+endTime+"','YYYY/MM/DD')");
		}
		psql.append(" order by to_char(t.fbizdate,'yyyy-MM-dd') desc");
		int psize = 100; //每页显示数
        int pindex=offset/psize;//+1  页码从0开始
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap= trainChargeService.selectPage(pindex, psql.toString(), psize);
		PageBean<TrainCharge> pb=new PageBean<>();
		pb.setPc(pindex); //页码
		Map<String, Object> paramMapCount=getPageBeanCount(psql.toString()); //取记录总数
		pb.setTr((int)paramMapCount.get("Pcount")); //记录总数
		pb.setPs(psize);
		pb.setBeanList((List<TrainCharge>)paramMap.get("v_cur")); //每页数据集
		return pb;
	}

	@SuppressWarnings("unchecked")
	/**
	 * 返回PageBean实体类  包括记录总数，页码，每页记录集等  dmz 20160921
	 * @return 返回PageBean实体类
	 * @throws Exception
	 */
	public PageBean<TrainCharge> getPageBean(HttpServletRequest request,String companyId,String beginTime,String endTime) throws Exception
	{

		int offset;//从第几条数据开始加载
		if(request.getParameter("pager.offset")==null){
			offset=0;
		}else{
			offset=Integer.parseInt(request.getParameter("pager.offset"));
		}
		//拼接SQL语句
		StringBuffer psql = new  StringBuffer();
		psql.append("select t.fid,t.fnumber,t.fdescription,to_char(t.fbizdate,'yyyy-MM-dd')fbizdate,u.name zdrName,us.name shName,t.cfbillstate,t.cfdycs,a.fname_l2 companyName ");
		psql.append(" from ct_ds_traincharge t left join t_e_user u  on t.fcreatorid=u.fid left join t_e_user us on t.fauditorid = us.fid left join ct_ds_admin a on t.cfficompanyid =a.fid where t.fcontrolunitid = '"+companyId+"'");
		psql.append(" and t.fbizdate between to_date('"+beginTime+"','YYYY/MM/DD') and to_date('"+endTime+"','YYYY/MM/DD')");
		psql.append(" order by to_char(t.fbizdate,'yyyy-MM-dd') desc");
		int psize = 30; //每页显示数
        int pindex=offset/psize;//+1  页码从0开始
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap= trainChargeService.selectPage(pindex, psql.toString(), psize);
		PageBean<TrainCharge> pb=new PageBean<>();
		pb.setPc(pindex); //页码
		Map<String, Object> paramMapCount=getPageBeanCount(psql.toString()); //取记录总数
		pb.setTr((int)paramMapCount.get("Pcount")); //记录总数
		pb.setPs(psize);
		pb.setBeanList((List<TrainCharge>)paramMap.get("v_cur")); //每页数据集
		return pb;
	}

	/**
	 * 取记录总数 dmz 20160921
	 * @param psql  SQL语句
	 * @return Map
	 * @throws Exception
	 */
	public Map<String, Object> getPageBeanCount(String psql) throws Exception
	{

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap=trainChargeService.selectPageCount(psql);
		return paramMap;
	}

	/**
	 * 导出Execl
	 *
	 * @param response
	 */
	@RequestMapping("/importTrainCharge")
	public void importTrainCharge(HttpServletResponse response, HttpServletRequest request,
								  String studentName, String cfidcardno, String cftjr, String beginTime, String endTime) {
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		List<Object> data = new ArrayList<>();

		Map<String,Object>date2=new HashMap<>();
		 String companyId=user.getFcompanyid();
		 if("GOSjULHhQN26IbdF5KXdwcznrtQ=".equals(companyId)){
			 //查询数据
			 List<TrainChargeEntry> trainChargeEntrys = trainChargeEntryService.selectTrainChargeByInfo(studentName.trim(), cfidcardno.trim(), cftjr.trim(), beginTime, endTime, user.getFcompanyid());

			 for (TrainChargeEntry trainChargeEntry : trainChargeEntrys) {

				 data.add(trainChargeEntry.getCfstudentno());//学员编码6(报名序号)
				 data.add(trainChargeEntry.getFbizdate());//业务日期2(缴费日期)
				 data.add(trainChargeEntry.getStudentName());//学员姓名7(姓名)
				 data.add(trainChargeEntry.getCfidcardno());//身份证号9
				 data.add(trainChargeEntry.getCfpxf().toString());//培训费
				 data.add(trainChargeEntry.getCfguifei().toString());//规费
				 data.add(" ");//jxk计时卡实在是找不到了
				 data.add(" ");//照相
				 data.add(" ");//考前训练收费 这个我真的是醉了
				 data.add(" ");//其他
				 Integer count=Integer.parseInt((Integer.parseInt(trainChargeEntry.getCfpxf()+"")+Integer.parseInt(trainChargeEntry.getCfguifei()+""))+"");
				 data.add(count);//合计
				 data.add(trainChargeEntry.getCftjr());//推荐人11
				 if(trainChargeEntry.getCfcash()!=null&&trainChargeEntry.getCfcard()!=null){
				     data.add("现金"+trainChargeEntry.getCfcash()+"刷卡"+trainChargeEntry.getCfcard()+"补交费");//缴费方式
				 }else if(trainChargeEntry.getCfcard()!=null){
					 data.add("刷卡补交费");//缴费方式
				 }else if(trainChargeEntry.getCfcash()!=null){
				 	data.add("现金补交费");//缴费方式
				 }else{
                    data.add("其他方式补交费或者欠费");//缴费方式
				 }
				 data.add("补交费");//备注
				 data.add(" ");//欠费
				 data.add(" ");//开票时间
				 data.add(" ");//刷卡开票金额
				 data.add(" ");//现金开票金额
				 data.add(" ");//合计
				 data.add(" ");//规费付款时间
				 data.add(" ");//发票时间
				 data.add(trainChargeEntry.getCfguifei());//上交规费金额
				 data.add(" ");//发票号码
				 data.add(" ");//规费备注
			 }
			 //头部数据
			 String head[] = {"报名序号", "缴费日期","姓名","身份证号","培训费","规费", "培训计时卡","照相","考前训练收费","其他","合计","推荐人","缴费方式","备注","欠费","开票时间","刷卡开票金额","现金开票金额","合计",
					 "规费付款时间","发票时间","上缴规费金额","发票号码","规费备注"

			 };
			 //长度
			 Integer length[] = {6500, 6000, 4500, 8800, 3500, 3500, 3500, 3500, 3500, 3500, 6500, 4500, 5000,5000 ,3500,6000,3500, 3500, 6000,
					 3000, 3000, 3000,4000,6500};

			 List<Object> data2= new ArrayList<>();

			 try {
				 //导出Excel
				 CommonExport.importExcelSum(response, "培训收费" + TimeFormat.getNowTime2() + ".xls", "培训收费", data, head, length,data2);
			 } catch (Exception e) {
				 e.printStackTrace();
			 }

		 }else{

		//查询数据
        List<TrainChargeEntry> trainChargeEntrys = trainChargeEntryService.selectTrainChargeByInfo(studentName.trim(), cfidcardno.trim(), cftjr.trim(), beginTime, endTime, user.getFcompanyid());

        for (TrainChargeEntry trainChargeEntry : trainChargeEntrys) {
			data.add(trainChargeEntry.getFnumber());//单据编号0
			data.add(trainChargeEntry.getCompanyName());//驾校1
			data.add(trainChargeEntry.getFbizdate());//业务日期2
			data.add(trainChargeEntry.getShName());//审核人3
			data.add(trainChargeEntry.getZdrName());//制单人名称4
            data.add(stateToString.billsState(trainChargeEntry.getCfbillstate()));//5
            data.add(trainChargeEntry.getCfstudentno());//学员编码6
			data.add(trainChargeEntry.getStudentName());//学员7
            data.add(stateToString.sex(trainChargeEntry.getCfsex()));//8
            data.add(trainChargeEntry.getCfidcardno());//身份证号9
			data.add(trainChargeEntry.getCfidcardaddress());//身份证地址10
			data.add(trainChargeEntry.getCftjr());//推荐人11
			data.add(trainChargeEntry.getCfclazz());//班级12
			Student student=studentService.queryStudentByIdCardNo(trainChargeEntry.getCfidcardno().toString(),companyId);
			List<Student> studentList=studentService.selectStudentByFid(student.getFid());
			data.add(studentList.get(0).getFcreatetime());//入学时间
			data.add(studentList.get(0).getCfslzjcxdh());//车型
			data.add(studentList.get(0).getCfdepartment());//职员部门
			data.add(trainChargeEntry.getCfclazzamount());//班级金额16
			data.add(trainChargeEntry.getCfyishou());//已收17
			data.add(trainChargeEntry.getCfysje());//应收金额18
			data.add(trainChargeEntry.getCfcash());//现金19
			data.add(trainChargeEntry.getCfcard());//刷卡20
			data.add(trainChargeEntry.getCfshje());//实收金额21
			data.add(trainChargeEntry.getCfyhje());//优惠金额22
			data.add(trainChargeEntry.getCfqfje());//欠费金额23
			data.add(trainChargeEntry.getCfguifei());//规费24
			data.add(trainChargeEntry.getCfpxf());//培训费25
			data.add(trainChargeEntry.getCfguazhang());//挂账26
			data.add(trainChargeEntry.getCfyhzz());//银行转账27
			data.add(trainChargeEntry.getCfdycs());//打印次数28
			data.add(trainChargeEntry.getSspxf());//实收培训费29
			data.add(trainChargeEntry.getCfyhj());//优惠券30
        }
		//头部数据
		String head[] = {"单据编码", "驾校", "业务日期", "审核人名称", "制单人名称", "单据状态", "学员编码", "学员", "性别", "身份证号", "身份证地址", "推荐人", "班级", "入学时间","车型","部门","现金","班级金额", "已收", "应收金额",
				 "刷卡", "实收金额", "优惠金额", "欠费金额", "规费", "培训费", "挂账", "银行转账", "打印次数", "实收培训费", "优惠券"};
		//长度
		Integer length[] = {6500, 6000, 3000, 3000, 3000, 3000, 6200, 2600, 1500, 5000, 6500, 2600, 4000,4200 ,2600,3000,3000, 3000, 3000, 3000, 3000, 3000, 3000, 3000, 3000, 3000, 3000, 3000,3000,3500, 3000};


		List<Object> data2= listForSum(data,head,16,10);

		try {
			//导出Excel
			CommonExport.importExcelSum(response, "培训收费" + TimeFormat.getNowTime2() + ".xls", "培训收费", data, head, length,data2);
		} catch (Exception e) {
			e.printStackTrace();
		}
	  }
	}

	/**
	 *统计方法(完全相连)
	 * @param list1 完成遍历的集合
	 * @param head  表头
	 * @param num   求和的第一个字段的下标
	 * @param count  需要增加多少个字段
	 * @return
	 */
	public List<Object> listForSum(List<Object> list1,String[] head,int num,int count) {
        Double money = 0.00;
        List<Object> list = new ArrayList<>();
        DecimalFormat df = new DecimalFormat("#.00");
        list.add("合计：");
        for (int i = 0; i < num - 1; i++) {
            list.add(" ");
        }

        for (int i = 0; i < count; i++) {

            for (int j = 0; j < list1.size() / head.length; j++) {

                if (list1.get(num + head.length * j) != null && !"".equals(list1.get(num + head.length * j))) {
                    money += Double.parseDouble(list1.get(num + head.length * j) + "");

                } else {
                    money += 0.00;
                }
            }
			if(money==0.00||money==null){
				list.add("0.00");
			}else{
				if(".00".equals(df.format(money))){
					list.add("");
				}else{

				list.add(df.format(money));
				}
			}
            num++;
            money = 0.00;
        }
//        碰见为空的了

       list.add("");
       for (int j = 0; j < list1.size() / head.length; j++) {
            if (list1.get(num + head.length * j) != null && !"".equals(list1.get(num + head.length * j))) {
                money += Double.parseDouble(list1.get(num + head.length * j) + "");
            } else {
                money += 0.00;
            }

        }
        list.add(df.format(money));
		money=0.00;

        //处理不相连的情况
        list.add("");
            for(int j=0;j<list1.size() / head.length;j++){
                if(list1.get(head.length*(j+1)-2)!=null&&!"".equals(list1.get(head.length*(j+1)-2))){
                    money+= Double.parseDouble(list1.get(head.length*(j+1)-2)+"");
                }else {
                    money += 0.00;
                }
            }
            if(".00".equals(df.format(money))){
               list.add("");
            }else{
                list.add(df.format(money));
            }

         money=0.00;
		for(int j=0;j<list1.size() / head.length;j++){
			if(list1.get(head.length*(j+1)-1)!=null&&!"".equals(list1.get(head.length*(j+1)-1))){
				money+= Double.parseDouble(list1.get(head.length*(j+1)-1)+"");
			}else {
				money += 0.00;
			}
		}
		if(money==0.00||money==null){
			list.add("0.00");
		}else{
			list.add(df.format(money));
		}
            return list;
    }
        /**
         * 统计方法(不完全相连)
         * @param list1
         * @param head
         * @param num 相连的首个下标
         * @param count
         * @param Interval 间隔是多少
         * @return
         */
//    public List<String> listForSum(List<Object> list1,String[] head,int num,int nextNum,int count,int Interval){
//
//        Double money=0.0;
//
//        List<String>list=new ArrayList<>();
//        DecimalFormat df = new DecimalFormat("#.00");
//        list.add("合计：");
//        Boolean isLinked=false;
//        Boolean usefulof=false;
//        int maxNum=num+count;
//        //处理相连的情况下
//        for(int i=0;i<head.length;i++){
//            if(i>=num&&i<=maxNum){
//                usefulof=true;
//            }else if(i==maxNum+Interval){
//                usefulof=true;
//            }
//
//
//            if(maxNum-num>=0){
//                isLinked=true;
//            }
//
//             if(usefulof){
//
//                if(isLinked) {
//                    for (int j = 0; j < list1.size() / head.length; j++) {
//
//                        if (list1.get(num + head.length * j) != null && !"".equals(list1.get(num + head.length * j))) {
//                            money += Double.parseDouble(list1.get(num + head.length * j).toString());
//
//                        } else {
//                            money += 0.0;
//                        }
//                    }
//                    list.add(df.format(money));
//                    num++;
//                    money = 0.0;
//             }else{
//                    for (int j = 0; j < list1.size() / head.length; j++) {
//
//                        if (list1.get(num + head.length * j) != null && !"".equals(list1.get(num + head.length * j))) {
//                            money += Double.parseDouble(list1.get(num + head.length * j).toString());
//
//                        } else {
//                            money += 0.0;
//                        }
//                    }
//                    list.add(df.format(money));
//                    num++;
//                    money = 0.0;
//                }
//            }else{
//                list.add(" ");
//                num++;
//            }
//        }
//        //处理不相连的情况
//        num=2;
//        for(int i=0;i<num+1;i++){
//            for (int j=0;j<list1.size()/head.length;j++){
//
//                if(list1.get(head.length*(j+1)-num)!=null&&!"".equals(list1.get(head.length*(j+1)-num))){
//                    money += Double.parseDouble(list1.get(head.length*(j+1)-num).toString());
//
//                }else{
//                    money += 0.0;
//                }
//            }
//            if(money==0.0||money==null){
//                list.add(head[head.length-num]+":0.0");
//            }else{
//                list.add(head[head.length-num]+":"+(df.format(money)));
//            }
//            num--;
//            money=0.0;
//        }
//
//
//        return list;
//    }
}
